package com.molichuxing.gateway.bff.car.services.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.gateway.property.AccidentReportStatusEnum;
import com.molichuxing.gateway.property.AccidentSettleStatusEnum;
import com.molichuxing.services.business.dto.response.*;
import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.infrastructure.dto.response.CarDto;
import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.gateway.bff.car.convertor.Convert;
import com.molichuxing.gateway.bff.car.entity.request.create.AccidentCaseCreateBffVo;
import com.molichuxing.gateway.bff.car.entity.request.create.AccidentCreateBffVo;
import com.molichuxing.gateway.bff.car.entity.request.create.AccidentImageCreateVo;
import com.molichuxing.gateway.bff.car.entity.response.AccidentCaseDetailVo;
import com.molichuxing.gateway.bff.car.entity.response.AccidentDetailVo;
import com.molichuxing.gateway.bff.car.entity.response.AccidentOrderCarInfoVo;
import com.molichuxing.gateway.bff.car.entity.response.AccidentPagedVo;
import com.molichuxing.gateway.bff.car.entity.response.AccidentVo;
import com.molichuxing.gateway.bff.car.services.AccidentBffService;
import com.molichuxing.gateway.utils.RequestAttrUtil;
import com.molichuxing.services.business.dto.request.create.AccidentCaseCreateBizDto;
import com.molichuxing.services.business.dto.request.create.AccidentCreateBizDto;
import com.molichuxing.services.business.dto.request.create.AccidentImageCreateBizDto;
import com.molichuxing.services.business.service.CarAccidentBizService;
import com.molichuxing.services.business.service.OrderBizService;
import com.molichuxing.services.infrastructure.dto.request.create.AccidentCaseCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.AccidentCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.AccidentDriveCreateDto;

/**
 * @Author: renzhengyu
 * @Description:
 * @Date: Created in 15:08 2019/9/19
 * @Modified By:
 **/
@Service("accidentBffService")
public class AccidentBffServiceImpl implements AccidentBffService {
    private static final Logger logger = LoggerFactory.getLogger(AccidentBffServiceImpl.class);

    @Resource
    private CarService carService;

    @Resource
    private AccidentService accidentService;

    @Resource
    private CarAccidentBizService carAccidentBizService;

    @Resource
    private OrderBizService orderBizService;

    @Resource
    private AccidentDriveService accidentDriveService;

    @Resource
    private StoreService storeService;

    @Resource
    private AccidentCaseService accidentCaseService;

    @Resource
    private InsuranceService insuranceService;

    @Resource
    private InsuranceCompanyService insuranceCompanyService;
    @Resource
    private RegionService regionService;
    @Resource
    private OrderDeliveryService orderDeliveryService;


    @Override
    public Paged<AccidentPagedVo> getCarAccidentAppPage(Integer resultType, Integer pageNum, Integer pageSize) throws Exception {
        Paged<AccidentPagedVo> accidentPagedVoPaged = new Paged<>(null, 0, pageSize);

        //获取当前登录的用户id
        Integer userId = RequestAttrUtil.getCurrentUserId();
        if(null == userId){
            throw new Exception("用户未登录");
        }
        
        Boolean isReturn= false;
        if(resultType == null || resultType == 1) {
        	isReturn = false;
        }else {
        	isReturn = true;
        }
        //查询用户订单编号
        List<Long> orderCodes = orderBizService.getCarOrderCodeByUser(userId,isReturn);
        if(null == orderCodes || orderCodes.isEmpty()) {
        	return accidentPagedVoPaged;
        }
        
        Paged<AccidentDto> accidentDtoPaged = accidentService.getCarAccidentAppPage(orderCodes,userId, pageNum, pageSize);
        if (null == accidentDtoPaged) {
            return accidentPagedVoPaged;
        }
        BeanUtils.copyProperties(accidentDtoPaged, accidentPagedVoPaged);
        if(null == accidentDtoPaged.getList()){
            return accidentPagedVoPaged;
        }

        List<AccidentPagedVo> accidentPagedVoList = new ArrayList<>();
        AccidentPagedVo accidentPagedVo = null;
        for (AccidentDto accidentDto :accidentDtoPaged.getList()) {
            accidentPagedVo = new AccidentPagedVo();
            BeanUtils.copyProperties(accidentDto, accidentPagedVo);
            //获取车辆基础信息
            CarDto carDto = carService.getCarById(accidentDto.getCarId());
            if(null == carDto){
                throw new Exception("非法入参");
            }
            RegionInfoDto regionInfoDto = regionService.getCityNameByAreaId(accidentDto.getRegionId());
            if(null == regionInfoDto){
                throw new Exception("非法入参");
            }
            String regionIdName = regionInfoDto.getCityFullName().concat(regionInfoDto.getAreaFullName());
            if(null != regionInfoDto.getProvinceFullName()){
                regionIdName = regionInfoDto.getProvinceFullName() + regionIdName;
            }
            accidentPagedVo.setRegionName(regionIdName);
            accidentPagedVo.setLicencePlate(carDto.getLicencePlate());
            accidentPagedVo.setIsCasualty(accidentDto.getIsCasualty()? CarAccidentCasualtyEnum.YES.getValue():CarAccidentCasualtyEnum.NO.getValue());
            accidentPagedVo.setStatus(accidentDto.getStatus());
            switch(accidentDto.getStatus()){
                case 1:
                    accidentPagedVo.setReportStatus(accidentDto.getStatus());
                    break;
                case 2:
                    accidentPagedVo.setReportStatus(accidentDto.getStatus());
                    accidentPagedVo.setSettleStatus(AccidentSettleStatusEnum.UNSUBMIT.getValue());
                    break;
                case 3:
                    accidentPagedVo.setReportStatus(AccidentReportStatusEnum.CONFIRM.getValue());
                    accidentPagedVo.setSettleStatus(AccidentSettleStatusEnum.UNCONFIRMED.getValue());
                    break;
                case 4:
                    accidentPagedVo.setReportStatus(AccidentReportStatusEnum.CONFIRM.getValue());
                    accidentPagedVo.setSettleStatus(AccidentSettleStatusEnum.CONFIRM.getValue());
                    break;
                case 5:
                    accidentPagedVo.setReportStatus(accidentDto.getStatus());
                    break;
                default:
                    break;
            }


            accidentPagedVoList.add(accidentPagedVo);
        }
        accidentPagedVoPaged.setList(accidentPagedVoList);

        return accidentPagedVoPaged;
    }

    @Override
    public AccidentDetailVo getAppAccident(Integer accidentId) throws Exception {
        AccidentDetailVo accidentDetailVo= new AccidentDetailVo();

        AccidentDetailAppBizDto accidentDetailAppBizDto = carAccidentBizService.getAppAccident(accidentId);
        if(null == accidentDetailAppBizDto || null== accidentDetailAppBizDto.getAccidentAppBizDto() || null == accidentDetailAppBizDto.getAccidentDriveAppBizDto()){
            throw new Exception("非法入参，信息为空");
        }

        //基础信息
        AccidentVo accidentVo = Convert.toAccidentVo(accidentDetailAppBizDto.getAccidentAppBizDto());
        //获取车辆基础信息
        CarDto carDto = carService.getCarById(accidentVo.getCarId());
        if(null == carDto){
            throw new Exception("非法入参");
        }
        RegionInfoDto regionInfoDto = regionService.getCityNameByAreaId(accidentVo.getRegionId());
        if(null == regionInfoDto){
            throw new Exception("非法入参");
        }

        //查询该车辆的提车时间
        OrderDeliveryBizDto orderDeliveryDto = orderBizService.getDelivery(accidentVo.getOrderCode());
        if(null == orderDeliveryDto){
            throw new Exception("提车信息为空");
        }
        //获取保险名称
        List<InsuranceDto> insuranceDtoList = insuranceService.getInsuranceByCarId(accidentVo.getCarId(),null);
        if(null != insuranceDtoList && insuranceDtoList.size() > 0){
            for (InsuranceDto insuranceDto:insuranceDtoList) {
                if(CarInsuranceTypeEnum.COMPULSORY_INSURANCE.getValue() == insuranceDto.getType() && insuranceDto.getEndTime().isAfter(LocalDateTime.now())){
                    InsuranceCompanyDto insuranceCompanyDto = insuranceCompanyService.getInsuranceCompanyName(insuranceDto.getInsuranceCompanyId());
                    if(null != insuranceCompanyDto){
                        accidentVo.setCompulsory(insuranceCompanyDto.getName());
                    }
                }
                if(CarInsuranceTypeEnum.COMMERCIAL_INSURANCE.getValue() == insuranceDto.getType() && insuranceDto.getEndTime().isAfter(LocalDateTime.now())){
                    InsuranceCompanyDto insuranceCompanyDto = insuranceCompanyService.getInsuranceCompanyName(insuranceDto.getInsuranceCompanyId());
                    if(null != insuranceCompanyDto){
                        accidentVo.setCommercial(insuranceCompanyDto.getName());
                    }
                }
            }
        }
        String regionIdName = regionInfoDto.getCityFullName().concat(regionInfoDto.getAreaFullName());
        if(null != regionInfoDto.getProvinceFullName()){
            regionIdName = regionInfoDto.getProvinceFullName() + regionIdName;
        }
        accidentVo.setStoreId(orderDeliveryDto.getStoreId());
        accidentVo.setDeliveryTime(orderDeliveryDto.getDeliveryTime());
        accidentVo.setRegionName(regionIdName);
        accidentVo.setLicencePlate(carDto.getLicencePlate());
        accidentDetailVo.setAccidentVo(accidentVo);
        //驾驶人信息
        accidentDetailVo.setAccidentDriveVo(Convert.toAccidentDriveVo(accidentDetailAppBizDto.getAccidentDriveAppBizDto()));

        //上传图片信息
        accidentDetailVo.setAccidentImageVoList(Convert.toAccidentImageVo(accidentDetailAppBizDto.getAccidentImageAppBizDtoList()));

        return accidentDetailVo;
    }

    @Override
    public AccidentCaseDetailVo getAccidentCaseDetail(Integer accidentId) throws Exception {
        AccidentCaseDetailVo accidentCaseDetailVo = null;
        AccidentCaseDetailAppDto accidentCaseDetailAppDto = carAccidentBizService.getAccidentCaseDetailApp(accidentId);
        if(null == accidentCaseDetailAppDto || null == accidentCaseDetailAppDto.getAccidentCaseAppDto()){
            throw new Exception("非法入参，信息为空");
        }
        accidentCaseDetailVo = new AccidentCaseDetailVo();
        //结案信息
        accidentCaseDetailVo.setAccidentCaseVo(Convert.toaccidentCaseDetailVo(accidentCaseDetailAppDto.getAccidentCaseAppDto()));
        //上传图片信息
        accidentCaseDetailVo.setAccidentImageVoList(Convert.toAccidentImageVo(accidentCaseDetailAppDto.getAccidentImageAppBizDto()));

        return accidentCaseDetailVo;
    }

    @Override
    public List<AccidentOrderCarInfoVo> getLicencePlateByUser() throws Exception {
        List<AccidentOrderCarInfoVo> accidentOrderCarInfoVoList = null;
        //获取当前登录的用户id
        Integer userId = RequestAttrUtil.getCurrentUserId();
        if(null == userId){
            throw new Exception("用户未登录");
        }
		List<OrderCarInfoAppDto> orderCarInfoAppDtoList = orderBizService.getCarIdsByUser(userId,
				OrderExclusivelStatusEnum.TRADE_USE.getValue());
        if(null == orderCarInfoAppDtoList || orderCarInfoAppDtoList.size() <= 0){
            return accidentOrderCarInfoVoList;
        }
        accidentOrderCarInfoVoList = new ArrayList<>();
        AccidentOrderCarInfoVo accidentOrderCarInfoVo = null;
        for (OrderCarInfoAppDto orderCarInfoAppDto:orderCarInfoAppDtoList) {
            accidentOrderCarInfoVo = new AccidentOrderCarInfoVo();
            BeanUtils.copyProperties(orderCarInfoAppDto, accidentOrderCarInfoVo);
            //获取车辆基础信息
            CarDto carDto = carService.getCarById(orderCarInfoAppDto.getCarId());
            if(null == carDto){
                throw new Exception("非法入参");
            }

            List<InsuranceDto> insuranceDtoList = insuranceService.getInsuranceByCarId(orderCarInfoAppDto.getCarId(),null);
            if(null != insuranceDtoList && insuranceDtoList.size() > 0){
                for (InsuranceDto insuranceDto:insuranceDtoList) {
                    if(CarInsuranceTypeEnum.COMPULSORY_INSURANCE.getValue() == insuranceDto.getType() && insuranceDto.getEndTime().isAfter(LocalDateTime.now())){
                        InsuranceCompanyDto insuranceCompanyDto = insuranceCompanyService.getInsuranceCompanyName(insuranceDto.getInsuranceCompanyId());
                        if(null != insuranceCompanyDto){
                            accidentOrderCarInfoVo.setCompulsory(insuranceCompanyDto.getName());
                        }
                    }
                    if(CarInsuranceTypeEnum.COMMERCIAL_INSURANCE.getValue() == insuranceDto.getType() && insuranceDto.getEndTime().isAfter(LocalDateTime.now())){
                        InsuranceCompanyDto insuranceCompanyDto = insuranceCompanyService.getInsuranceCompanyName(insuranceDto.getInsuranceCompanyId());
                        if(null != insuranceCompanyDto){
                            accidentOrderCarInfoVo.setCommercial(insuranceCompanyDto.getName());
                        }
                    }
                }
            }


            accidentOrderCarInfoVo.setLicencePlate(carDto.getLicencePlate());

            accidentOrderCarInfoVoList.add(accidentOrderCarInfoVo);
        }

        return accidentOrderCarInfoVoList;
    }

    @Override
    public Boolean createAccidentCreateBff(AccidentCreateBffVo accidentCreateBffVo) throws Exception ,BizException{

        if(null != accidentCreateBffVo.getAccidentCreateVo().getId()){
            AccidentDto accidentDto = accidentService.getCarAccident(accidentCreateBffVo.getAccidentCreateVo().getId());
            if(null == accidentDto){
                throw new Exception("非法入参");
            }
            if(!accidentDto.getVersion().equals(accidentCreateBffVo.getAccidentCreateVo().getVersion())){
                throw new BizException(ResponseCodeEnum.ABNORMAL_ERROR.getCode(), "状态已发生变化，无法提交");
            }
        }

        AccidentCreateBizDto accidentCreateBizDto = new AccidentCreateBizDto();
        AccidentCreateDto accidentCreateDto = new AccidentCreateDto();
        AccidentDriveCreateDto accidentDriveCreateDto = new AccidentDriveCreateDto();
        //基础信息
        BeanUtils.copyProperties(accidentCreateBffVo.getAccidentCreateVo(), accidentCreateDto);
        //根据门店id查询经销商信息
        StoreDto storeDto = storeService.getStoreById(accidentCreateBffVo.getAccidentCreateVo().getStoreId());
        if(null == storeDto){
            throw new Exception("非法入参");
        }
        //获取当前登录的用户id
        Integer userId = RequestAttrUtil.getCurrentUserId();
        if(null == userId){
            throw new Exception("用户未登录");
        }
        accidentCreateDto.setCode(DateUtil.formatLocalDateNow()+(int)((Math.random()*9+1)*10000));
        accidentCreateDto.setUserId(userId);
        accidentCreateDto.setDealerId(storeDto.getDealerId());
        accidentCreateDto.setStatus(CarAccidentStatusEnum.ACCIDENT_NOT_CONFIRMED.getValue());
        accidentCreateDto.setAccidentTime(DateUtil.parseDateTime(accidentCreateBffVo.getAccidentCreateVo().getAccidentTime()));
        accidentCreateDto.setIsCasualty(accidentCreateBffVo.getAccidentCreateVo().getIsCasualty() == 1? true:false);
        accidentCreateDto.setIsDamage(accidentCreateBffVo.getAccidentCreateVo().getIsDamage() == 1? true:false);
        accidentCreateDto.setReportTime(LocalDateTime.now());
        accidentCreateBizDto.setAccidentCreateDto(accidentCreateDto);
        //驾驶人信息
        BeanUtils.copyProperties(accidentCreateBffVo.getAccidentDriveCreateVo(), accidentDriveCreateDto);
        accidentCreateBizDto.setAccidentDriveCreateDto(accidentDriveCreateDto);

        if(null != accidentCreateBffVo.getAccidentImageCreateVoList() && accidentCreateBffVo.getAccidentImageCreateVoList().size() > 0){
            List<AccidentImageCreateBizDto> accidentImageCreateBizDtoList = new ArrayList<>();
            AccidentImageCreateBizDto accidentImageCreateBizDto = null;
            for (AccidentImageCreateVo accidentImageCreateVo:accidentCreateBffVo.getAccidentImageCreateVoList()) {
                accidentImageCreateBizDto = new AccidentImageCreateBizDto();
                BeanUtils.copyProperties(accidentImageCreateVo, accidentImageCreateBizDto);
                accidentImageCreateBizDtoList.add(accidentImageCreateBizDto);
            }
            accidentCreateBizDto.setAccidentImageCreateVoList(accidentImageCreateBizDtoList);
        }
        Boolean flag = carAccidentBizService.createAccidentCreateBiz(accidentCreateBizDto);
        if(!flag){
            throw new Exception("失败");
        }
        return flag;
    }

    @Override
    public Boolean createAccidentCaseCreateBff(AccidentCaseCreateBffVo accidentCaseCreateBffVo) throws Exception,BizException {

        AccidentDto accidentDto = accidentService.getCarAccident(accidentCaseCreateBffVo.getAccidentCaseCreateVo().getId());
        if(null == accidentDto){
            throw new Exception("非法入参");
        }
        AccidentCaseCreateBizDto accidentCaseCreateBizDto = new AccidentCaseCreateBizDto();
        //结案信息
        AccidentCaseCreateDto accidentCaseCreateDto = Convert.toAccidentCaseCreateDto(accidentCaseCreateBffVo.getAccidentCaseCreateVo());
        accidentCaseCreateDto.setCode(accidentDto.getCode());
        accidentCaseCreateDto.setSettleTime(LocalDateTime.now());
        accidentCaseCreateBizDto.setAccidentCaseCreateDto(accidentCaseCreateDto);

        //图片信息
        if(null != accidentCaseCreateBffVo.getAccidentImageCreateVoList() && accidentCaseCreateBffVo.getAccidentImageCreateVoList().size() > 0){
            List<AccidentImageCreateBizDto> accidentImageCreateBizDtoList = new ArrayList<>();
            AccidentImageCreateBizDto accidentImageCreateBizDto = null;
            for (AccidentImageCreateVo accidentImageCreateVo:accidentCaseCreateBffVo.getAccidentImageCreateVoList()) {
                accidentImageCreateBizDto = new AccidentImageCreateBizDto();
                BeanUtils.copyProperties(accidentImageCreateVo, accidentImageCreateBizDto);
                accidentImageCreateBizDtoList.add(accidentImageCreateBizDto);
            }
            accidentCaseCreateBizDto.setAccidentImageCreateVoList(accidentImageCreateBizDtoList);
        }

        Boolean flag = carAccidentBizService.createAccidentCaseCreateBiz(accidentCaseCreateBizDto);
        if(!flag){
            throw new Exception("失败");
        }

        return flag;
    }


}
